<template>
  <div class="quota-maintenance-container">
    <div class="page-header">
      <h2>额度消耗维护</h2>
    </div>

    <!-- 默认规则说明 - 简化版 -->
    <a-alert class="default-rules" type="info" show-icon banner>
      <template #message>
        <span
          >默认额度消耗规则：<strong>周一、周五</strong>扣除
          <strong>0.5</strong> 额度，<strong>周二至周四</strong>扣除
          <strong>1</strong> 额度。以下表格中的特殊规则将覆盖默认设置。</span
        >
      </template>
    </a-alert>

    <!-- 添加周末说明 -->
    <!-- <div class="date-info">
      <a-alert type="warning" show-icon message="周末不可设置额度规则" style="margin-bottom: 8px;" />
    </div> -->

    <!-- 添加新规则表单 -->
    <div class="add-rule-form">
      <a-form layout="inline" :model="formState">
        <a-form-item
          label="日期"
          name="date"
          :rules="[{ required: true, message: '请选择日期' }]"
        >
          <a-date-picker
            v-model:value="formState.date"
            :disabledDate="disabledDate"
            placeholder="选择日期"
            @change="handleDateChange"
          />
        </a-form-item>
        <a-form-item
          label="额度"
          name="quota"
          :rules="[{ required: true, message: '请输入额度' }]"
        >
          <a-input-number
            v-model:value="formState.quota"
            :min="0"
            :max="10"
            :step="0.5"
            placeholder="输入额度"
          />
        </a-form-item>
        <a-form-item label="备注" name="name">
          <a-input
            v-model:value="formState.name"
            placeholder="输入备注信息"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="addRule" :loading="addLoading">
            <template #icon><PlusOutlined /></template>
            添加规则
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 特定日期规则表格 -->
    <a-table
      :columns="columns"
      :data-source="quotaRules"
      :pagination="false"
      :loading="tableLoading"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <!-- 日期列 -->
        <template v-if="column.dataIndex === 'date'">
          {{ record.date }}
          <a-tag v-if="isWeekend(record.date)" color="blue">周末</a-tag>
          <a-tag v-if="isHoliday(record.date)" color="red">节假日</a-tag>
        </template>

        <!-- 操作列 -->
        <template v-if="column.dataIndex === 'action'">
          <a-popconfirm
            title="确定删除此规则?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="deleteRule(record.id)"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import {
  getSpecialDateList,
  addSpecialDate,
  deleteSpecialDate,
} from "../api/index";
// 表单状态
const formState = reactive({
  date: null,
  booking_cost: 1,
  name: "",
});

// 加载状态
const tableLoading = ref(false);
const addLoading = ref(false);

// 表格数据
const quotaRules = ref([]);

// 表格列定义
const columns = [
  {
    title: "日期",
    dataIndex: "date",
    key: "date",
    sorter: (a, b) => new Date(a.date) - new Date(b.date),
  },
  {
    title: "星期",
    dataIndex: "week",
    key: "weekday",
  },
  {
    title: "额度",
    dataIndex: "booking_cost",
    key: "booking_cost",
    sorter: (a, b) => a.booking_cost - b.booking_cost,
  },
  {
    title: "备注",
    dataIndex: "name",
    key: "name",
    ellipsis: true,
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "createdAt",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
  },
];
const getList = async () => {
  tableLoading.value = true;
  const res = await getSpecialDateList();
  quotaRules.value = res.data;
  console.log(res);
  tableLoading.value = false;
  message.success("额度规则加载完成");
};
// 禁用过去的日期和周末
const disabledDate = (current) => {
  // 禁用过去的日期
  const isPastDate = current && current < new Date().setHours(0, 0, 0, 0);

  // 禁用周末 (0=周日, 6=周六)
  const isWeekend = current && (current.day() === 0 || current.day() === 6);

  return isPastDate || isWeekend;
};

// 判断是否周末
const isWeekend = (dateString) => {
  const date = new Date(dateString);
  const day = date.getDay();
  return day === 0 || day === 6;
};

// 判断是否节假日（模拟数据）
const isHoliday = (dateString) => {
  // 这里可以接入实际的节假日API或配置
  const holidays = ["2023-10-01", "2023-10-02", "2023-10-03"];
  return holidays.includes(dateString);
};

// 获取星期几文本
const getWeekdayText = (dateString) => {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const date = new Date(dateString);
  return weekdays[date.getDay()];
};

// 选择日期时检查
const handleDateChange = (date) => {
  if (date) {
    const day = date.day();
    if (day === 0 || day === 6) {
      message.warning("周末不能设置额度规则");
      formState.date = null;
    }
  }
};

// 添加规则
const addRule = () => {
  if (!formState.date || formState.booking_cost === null) {
    message.error("请填写完整信息");
    return;
  }

  addLoading.value = true;

  // 格式化日期
  const formattedDate = formState.date.format("YYYY-MM-DD");

  // 检查日期是否已存在
  const exists = quotaRules.value.some((rule) => rule.date === formattedDate);
  if (exists) {
    message.error("该日期已有规则，请直接修改或先删除");
    addLoading.value = false;
    return;
  }
  const params = {
    date: formattedDate,
    booking_cost: formState.booking_cost,
    name: formState.name || "-",
  };
  addSpecialDate(params)
    .then((res) => {
      message.success("规则添加成功");
      console.log(res);
      getList();
      // 重置表单
      formState.date = null;
      formState.booking_cost = 1;
      formState.name = "";
      addLoading.value = false;
    })
    .catch((err) => {
      message.error("规则添加失败");
      addLoading.value = false;
    });
};

// 删除规则
const deleteRule = (id) => {
  tableLoading.value = true;
  deleteSpecialDate(id).then(() => {
    message.success("规则已删除");
    tableLoading.value = false;
    getList();
  });
};

// 初始化数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.quota-maintenance-container {
  padding: 24px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.default-rules {
  margin-bottom: 16px;
}

/* 调整Alert内部样式 */
:deep(.default-rules .ant-alert-content) {
  margin: 0;
}

:deep(.default-rules .ant-alert-message) {
  font-size: 14px;
  line-height: 1.5;
}

.add-rule-form {
  background: #f5f5f5;
  padding: 24px;
  border-radius: 4px;
  margin-bottom: 24px;
}
</style>